import React, { Component } from 'react'
import { login } from '../../store/actions/login'
import classnames from "classnames"
import { connect } from 'react-redux';
import { useNavigate } from "react-router-dom"
import validator from "../../utils/login"
import {storageSet} from "../../utils/storage"
const myWithRouter = (Detail) => (props) => <Detail {...props} history={useNavigate()} />
class LoginForm extends Component {

  constructor() {
    super();
    this.state = {
      username: "admin",
      password: "123",
      errors: {},
      isLoading: false
    }
  };

  async onSubmit(e) {
    e.preventDefault();
    this.setState({ errors: {}, isLoading: true });
    if (this.isValidator.call(this)) {
      try {
        const { errors, success, token } = await this.props.login(this.state);
        storageSet("token", token, "sessionStorage");
        this.setState({ errors, isLoading: false });
        this.props.history('/');
      } catch ({errors}) {
        this.setState({ errors, isLoading: false });
      }
    }

  };

  onChange(e) {
    this.setState({ [e.target.name]: e.target.value });
  };
  isValidator() {
    const { errors, isValid } = validator(this.state);
    if (!isValid) {
      this.setState({ errors });
    }
    return isValid;
  }
  render() {
    const { errors, username, password, isLoading } = this.state;
    return (
      <form onSubmit={this.onSubmit.bind(this)}>
        <h1> Join our community</h1>
        {errors.from && <div className="alert alert-danger">{errors.from}</div>}
        <div className="form-group">
          <label htmlFor="">username</label>
          <input className={classnames('form-control', { 'is-invalid': errors.username })} type="text" name="username" value={username} onChange={this.onChange.bind(this)} />
          {errors.username && <span className='form-text text-danger'>{errors.username}</span>}
        </div>

        <div className="form-group">
          <label htmlFor="">password</label>
          <input className={classnames('form-control', { 'is-invalid': errors.password })} type="text" name="password" value={password} onChange={this.onChange.bind(this)} />
          {errors.password && <span className='form-text text-danger'>{errors.password}</span>}
        </div>

        <div className="form-group">
          <button disabled={isLoading} className="btn btn-primary btn-lg">登录</button>
        </div>
      </form>
    )
  }
};



export default connect(null, { login })(myWithRouter(LoginForm));
